package com.ews.onlineexchange.service.observer;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.URISyntaxException;

import javax.ejb.Asynchronous;
import javax.ejb.Stateless;
import javax.enterprise.event.Observes;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;
import javax.websocket.DeploymentException;

import com.ews.onlineexchange.enumType.RecordStatus;
import com.ews.onlineexchange.model.CalcMethod;
import com.ews.onlineexchange.model.ServiceSupplier;
import com.ews.onlineexchange.model.assess.AssessRecord;
import com.ews.onlineexchange.service.qualifier.AssessRecodOperationEvent;

@Stateless
public class AssessRecordOperationObserver {
	
	@Inject
	EntityManager entityManager;
	
	@Transactional
	@Asynchronous
	public void listenBestBulletinAgree(@Observes @AssessRecodOperationEvent Object[] objArray) throws DeploymentException, IOException, URISyntaxException {
		String assessRecordId = (String) objArray[0];
		AssessRecord assessRecord = entityManager.find( AssessRecord.class, assessRecordId );		
		RecordStatus recordStatus = (RecordStatus) objArray[1];
		assessRecord.setRecordStatus( recordStatus );
		entityManager.merge( assessRecord );
		
		if ( !recordStatus.equals( RecordStatus.Initaling ) ) {// 当状态为保留时，说明记录生效，根据dict进行加减分
																// ；当状态为删除时，说明记录失效，根据dict进行反向加减分
			ServiceSupplier supplier = assessRecord.getServiceSupplier();
			BigDecimal creditScore = supplier.getCreditScore();
			CalcMethod calcMethod = assessRecord.getDict().getCalcMethod();
			BigDecimal score = getFinalScore( assessRecord.getScore(), calcMethod, recordStatus );
			supplier.setCreditScore( creditScore.add( score ) );
			entityManager.merge( supplier );
		}
		
//		entityManager.merge(op);
	}
	
	public BigDecimal getFinalScore(BigDecimal score,CalcMethod calcMethod,RecordStatus recordStatus) {
		BigDecimal opposite = new BigDecimal(-1);
		if((calcMethod.equals(CalcMethod.Add) && recordStatus.equals(RecordStatus.Deleted)) 
				|| (calcMethod.equals(CalcMethod.Substract) && (recordStatus.equals(RecordStatus.Keeped)))) {
			score = score.divide(opposite);
		}
		
		return score;
	}
}
